﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AnesSystem.Models;
using AnesSystem.Controls;
using System.Windows.Media;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;
using System.Windows.Data;
using AnesSystem.Util;
using System.Windows.Threading;

namespace AnesSystem.ViewModels
{
    public class RealTimeItemCtrlViewModel : MultitonBaseViewModel
    {
        #region Variables

        private ObservableCollection<FrameworkElement> _canvasList;
        private List<FrameworkElement> _twList = new List<FrameworkElement>();
        private List<FrameworkElement> _mmhgList = new List<FrameworkElement>();
        private ObservableCollection<FrameworkElement> _autoShowCtrlList;
        private ObservableCollection<PatientVitalSignsModel> _allVitalList;
        private bool _isIBP = false;

        private int maxTW = 44;
        private int maxMMHG = 260;


        #endregion

        #region Constructor

        public RealTimeItemCtrlViewModel(int page)
        {
            CurPage = page;
            _canvasList = new ObservableCollection<FrameworkElement>();
            _autoShowCtrlList = new ObservableCollection<FrameworkElement>();
            _allVitalList = new ObservableCollection<PatientVitalSignsModel>();
            _twList = new List<FrameworkElement>();
            _mmhgList = new List<FrameworkElement>();
            InitHorizontalLins();
        }

        public ObservableCollection<FrameworkElement> CanvasList
        {
            get
            {
                return _canvasList;
            }

            set
            {
                _canvasList = value;
            }
        }

        public List<FrameworkElement> TwList
        {
            get
            {
                return _twList;
            }

            set
            {
                _twList = value;
            }
        }

        public List<FrameworkElement> MmhgList
        {
            get
            {
                return _mmhgList;
            }

            set
            {
                _mmhgList = value;
            }
        }

        public ObservableCollection<ConfigVitalSignsModel> RightVitalNameList
        {
            get
            {
                return AutoShowSignsCtrlViewModel.Instance.LineShowSignList;
            }
        }
        public ObservableCollection<ConfigVitalSignsModel> LeftVitalNameList
        {
            get
            {
                return AutoShowSignsCtrlViewModel.Instance.TableShowSignList;
            }
        }

        public List<PatientVitalSignsModel> AllVitalList
        {
            get
            {
                return (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel.AllVitalList;
            }
        }

        public ObservableCollection<FrameworkElement> AutoShowCtrlList
        {
            get
            {
                return _autoShowCtrlList;
            }

            set
            {
                _autoShowCtrlList = value;
            }
        }

        public VitalSignDataCache VitalSignData
        {
            get
            {
                return OperationDataPool.Instance.CurOperationData.VitalSignDataCacheDic[Constants.ISANES];
            }
        }


        #endregion

        #region Properties

        #endregion

        #region 依赖属性

        #endregion

        #region Event

        #endregion

        #region Private Methods

        private void CreateTW()
        {
            int value = maxTW;
            while (value > 20)
            {
                TextBlock text = new TextBlock();
                text.Text = value.ToString();
                text.FontSize = 16;
                text.TextAlignment = TextAlignment.Center;
                //              text.FontFamily = new FontFamily("Microsoft YaHei UI");
                TwList.Add(text);
                value -= 2;
            }
            RaisePropertyChanged("TwList");
        }

        private void CreateMMHG()
        {
            int value = maxMMHG;
            while (value > 0)
            {
                TextBlock text = new TextBlock();
                text.Text = value.ToString();
                text.FontSize = 16;
                text.TextAlignment = TextAlignment.Center;
                //               text.FontFamily = new FontFamily("Microsoft YaHei UI");
                //                text.TextAlignment = TextAlignment.Center;
                MmhgList.Add(text);
                value -= 20;
            }

            RaisePropertyChanged("MmhgList");
        }

        private void CreateAutoShowCtrls()
        {
            AutoShowCtrlList.Clear();
            foreach (var item in RightVitalNameList)
            {
                StackPanel panel = new StackPanel();
                panel.Orientation = Orientation.Horizontal;
                string fullName = "AnesSystem.Controls.";
                if (DataManager.Instance.Code2signs.ContainsKey(item.code))
                {
                    fullName = fullName + DataManager.Instance.Code2signs[item.code].iconCtrl;
                }
                Type type = Type.GetType(fullName);
                if (type == null) continue;
                RealVitalIcon ctrl = Activator.CreateInstance(Type.GetType(fullName)) as RealVitalIcon;
                panel.Children.Add(ctrl);
                TextBlock lb = new TextBlock();
                lb.Text = item.name;
                lb.FontFamily = new FontFamily("Microsoft YaHei UI");
                lb.Margin = new Thickness(5, 0, 0, 0);
                panel.Children.Add(lb);
                panel.DataContext = item;
                panel.Margin = new Thickness(5, 10, 0, 0);
                AutoShowCtrlList.Add(panel);
            }
            if (VitalSignData.IsSubResp)
            {
                AddSubRespSignsCtrl();
            }
            else
            {
                RemoveSubRespSignsCtrl();
            }
        }

        private void InitHorizontalLins()
        {
            int startX = 0;
            int startY = 0;
            for (int i = 0; i <= 28; i++)
            {
                Line line = new Line();
                line.X1 = startX;
                line.Y1 = startY;
                line.X2 = LocationUtil.RealTimeItem_Width * 48;
                line.Y2 = startY;
                startY += LocationUtil.RealTimeSignItem_Height;

                if (i % 2 != 0)
                {
                    line.Stroke = Brushes.Black;
                    line.StrokeThickness = 0.5;
                    line.StrokeDashArray = new DoubleCollection() { 2, 3 };
                    line.StrokeDashCap = PenLineCap.Flat;
                    line.StrokeEndLineCap = PenLineCap.Flat;
                    line.StrokeStartLineCap = PenLineCap.Flat;
                }
                else
                {
                    line.Stroke = Brushes.Black;
                    line.StrokeThickness = 0.5;
                }
                if (i == 0)
                {
                    continue;
                }
                CanvasList.Add(line);
            }
        }


        private void InitTimeLins()
        {
            try
            {
                int curPage = CurPage;
                DateTime anesRecordTime = DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime;
                DateTime startTime = anesRecordTime.AddHours((curPage - 1) * 4);
                int startX = 0;
                int startY = -10;
                DateTime date = startTime;
                for (int i = 0; i <= 48; i++)
                {
                    Line line = new Line();
                    line.X1 = startX;
                    line.Y1 = startY;
                    line.X2 = startX;
                    line.Y2 = LocationUtil.RealTimeSignItem_Height * 28;
                    startX += LocationUtil.RealTimeItem_Width;

                    if (i == 0 || i == 48)
                    {
                        line.Stroke = Brushes.Black;
                        line.StrokeThickness = 1;
                    }
                    else
                    {
                        if (date.Minute % 30 == 0)
                        {
                            line.Stroke = Brushes.Black;
                            line.StrokeThickness = 1;
                            if (date.Minute % 60 == 0)
                            {
                                line.Stroke = Brushes.Black;
                                line.StrokeThickness = 2;
                            }
                        }
                        else
                        {
                            line.Stroke = Brushes.Black;
                            line.StrokeDashArray = new DoubleCollection() { 2, 3 };
                            line.StrokeDashCap = PenLineCap.Flat;
                            line.StrokeEndLineCap = PenLineCap.Flat;
                            line.StrokeStartLineCap = PenLineCap.Flat;
                            line.StrokeThickness = 0.5;
                        }
                    }


                    CanvasList.Add(line);
                    date = date.AddMinutes(5);
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }

        /// <summary>
        /// 生成生命体征
        /// </summary>
        public void InitVitals()
        {
            try
            {
                //RealTimeSignShowCtrlViewModel viewmodel = DataManager.Instance.AnesRecordCtrl.ViewModel.AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel;
                //foreach (var item in viewmodel.DicAllVital)
                //{
                //    if (item.Key.Equals("0"))
                //    {
                //        foreach (var key in item.Value)
                //        {
                //            InitLineVitals(key.Value);
                //        }
                //    }
                //    else
                //    {
                //        foreach (var key in item.Value)
                //        {
                //            InitTableCellVitals(key.Value);
                //        }
                //    }
                //}



                var listGroup = AllVitalList.GroupBy(O => O.Group);
                foreach (var group in listGroup)
                {
                    if (DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign.First(O => O.code.Equals(group.First().Code.Equals(Constants.PARAM_SUB_RESP) ? Constants.PARAM_RESP_CODE : group.First().Code)).showWay == 1)
                    {
                        InitTableCellVitals(group.ToList());
                    }
                    else
                    {
                        InitLineVitals(group.ToList());
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }

        /// <summary>
        /// 配置呼吸
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private List<PatientVitalSignsModel> ConfigResp(List<PatientVitalSignsModel> list)
        {
            List<PatientVitalSignsModel> temp = new List<PatientVitalSignsModel>();
            var linq = list.GroupBy(O => O.CaptureTime);
            foreach (var item in linq)
            {
                PatientVitalSignsModel mode = new PatientVitalSignsModel();
                foreach (var p in item)
                {
                    if (Constants.PARAM_CTRL_RESP_CODE.Equals(p.Code))
                    {
                        mode = p;
                        break;
                    }
                    if (Constants.PARAM_SUB_RESP.Equals(p.Code))
                    {
                        mode = p;
                        break;
                    }
                    mode = p;
                }
                temp.Add(mode);
            }
            return temp.OrderBy(O => O.CaptureTime).ToList();
        }
        private void InitTableCellVitals(List<PatientVitalSignsModel> list)
        {
            if (list == null || list.Count == 0) return;
            string group = list.First().Group;
            //           int showWay = DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign.First(O => O.code.Equals(list.First().Code)).showWay;
            foreach (var item in list)
            {
                if (!ConfigVitalSignsDataGridViewModel.Instance.DicConfigVitalSings.ContainsKey(item.Code)) return;
                string fullName = "AnesSystem.Controls.TableCellCtrl";
                Type type = Type.GetType(fullName);
                if (type == null) continue;
                try
                {
                    RealVitalIcon ctrl = Activator.CreateInstance(Type.GetType(fullName)) as RealVitalIcon;
                    ctrl.DataContext = item;
                    ctrl.SelfVital = item;
                    ctrl.CurPage = CurPage;
                    ctrl.ToolTip = string.Format("时间:{0}\r\n{1}:{2}", item.CaptureTime.ToString(DateFormat.DATE_FORMAT_STR_HM), item.Name, item.ModValue);
                    string code = item.Code.Equals(Constants.PARAM_SUB_RESP) ? Constants.PARAM_RESP_CODE : item.Code;
                    if (!AutoShowSignsCtrlViewModel.Instance.TableViatal2Index.ContainsKey(code))
                    {
                        return;
                    }
                    ctrl.Index = AutoShowSignsCtrlViewModel.Instance.TableViatal2Index[code];

                    ctrl.SetPoint(item);
                    CanvasList.Add(ctrl);
                }
                catch (Exception ex)
                {
                    Common.LogHelper.Error(this.GetType(), ex);
                }
            }
        }

        private void InitLineVitals(List<PatientVitalSignsModel> list)
        {
            try
            {
                List<RealVitalIcon> listIcon = new List<RealVitalIcon>();
                if (list.Count == 0)
                {
                    return;
                }
                string group = list.First().Group;
                if (Constants.RESP.Equals(group))
                {
                    RemoveVitalItemByGroup(Constants.RESP);
                    list = ConfigResp(list);
                }

                //if (list[list.Count - 1].Code.Equals(Constants.PARAM_IBP_S) || list[list.Count - 1].Code.Equals(Constants.PARAM_IBP_M) || list[list.Count - 1].Code.Equals(Constants.PARAM_IBP_D))
                //{
                //    int index = FindNoEmptyValue(list, 0);
                //    if (index != -1)
                //    {
                //        PatientVitalSignsModel pvs = list[index];
                //        string fullName = "AnesSystem.Controls.YCXYITEMCtrl";
                //        Type type = Type.GetType(fullName);
                //        if (type != null)
                //        {
                //            PatientVitalSignsModel item = new PatientVitalSignsModel();
                //            item.Name = "有创";
                //            item.ModValue = pvs.ModValue;
                //            item.Group = "YCXY";
                //            item.CaptureTime = pvs.CaptureTime;
                //            try
                //            {
                //                RealVitalIcon ctrl = Activator.CreateInstance(Type.GetType(fullName)) as RealVitalIcon;
                //                ctrl.DataContext = item;
                //                ctrl.CurPage = CurPage;
                //                ctrl.SetPoint(item);
                //                CanvasList.Add(ctrl);
                //            }
                //            catch (Exception ex)
                //            {
                //                Common.LogHelper.Error(this.GetType(), ex);
                //            }
                //        }
                //    }
                //}

                foreach (var item in list)
                {
                    if (!ConfigVitalSignsDataGridViewModel.Instance.DicConfigVitalSings.ContainsKey(item.Code) && !(Constants.PARAM_SUB_RESP).Equals(item.Code)) return;
                    string fullName = "AnesSystem.Controls.";
                    if (DataManager.Instance.Code2signs.ContainsKey(item.Code))
                    {
                        fullName = fullName + DataManager.Instance.Code2signs[item.Code].iconCtrl;
                    }
                    Type type = Type.GetType(fullName);
                    if (type == null) continue;

                    try
                    {
                        RealVitalIcon ctrl = Activator.CreateInstance(Type.GetType(fullName)) as RealVitalIcon;
                        //                       ctrl.PreviewMouseDoubleClick += Ctrl_PreviewMouseDoubleClick;

                        ctrl.DataContext = item;
                        ctrl.CurPage = CurPage;
                        ctrl.ToolTip = string.Format("时间:{0}\r\n{1}:{2}", item.CaptureTime.ToString(DateFormat.DATE_FORMAT_STR_HM), item.Name, item.ModValue);

                        ctrl.SetPoint(item);
                        //                      CanvasList.Add(ctrl);
                        listIcon.Add(ctrl);
                    }
                    catch (Exception ex)
                    {
                        Common.LogHelper.Error(this.GetType(), ex);
                    }

                }
                CreateConnectionLine(group, listIcon);
                foreach (var item in listIcon)
                {
                    CanvasList.Add(item);
                }


            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }


        private void RefreshIBPText()
        {
            int count = CanvasList.Count;
            int delCount = 0;
            for (int i = 0; i < count; i++)
            {
                FrameworkElement ctrl = CanvasList[i - delCount];
                if (ctrl is TextBlock)
                {
                    CanvasList.RemoveAt(i - delCount);
                    delCount++;
                }
            }

            var listGroup = AllVitalList.GroupBy(O => O.Code);
            foreach (var group in listGroup)
            {
                List<PatientVitalSignsModel> list = group.ToList();
                if (list[list.Count - 1].Code.Equals(Constants.PARAM_IBP_S) || list[list.Count - 1].Code.Equals(Constants.PARAM_IBP_M) || list[list.Count - 1].Code.Equals(Constants.PARAM_IBP_D))
                {
                    int flag = FindNoEmptyValue(list, 0);
                    PatientVitalSignsModel pvs = null;
                    if (flag != -1)
                    {
                        pvs = list[flag];
                        ConfigVitalSignsModel cvs = null;
                        foreach (var item in DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign)
                        {
                            if (item.code.Equals(pvs.Code))
                            {
                                if (DataManager.Instance.Code2signs.ContainsKey(pvs.Code))
                                {
                                    cvs = DataManager.Instance.Code2signs[item.code];
                                }
                                break;
                            }
                        }
                        if (cvs != null && cvs.showWay == Constants.BEDSIDE_SHOW_METHOD_TREND)
                        {
                            CreatiBPCtrl(pvs);
                        }

                    }
                }

            }

        }

        private void CreatiBPCtrl(PatientVitalSignsModel pvs)
        {
            TextBlock ibpText = new TextBlock();
            ibpText.Text = "有创";
            double left = CalValue2Xplot(pvs) - 5;
            double top = CalValue2Yplot(pvs) - 20;
            Canvas.SetLeft(ibpText, left);
            Canvas.SetTop(ibpText, top);
            CanvasList.Add(ibpText);
        }

        private void Ctrl_PreviewMouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            PatientVitalSignsModel p = (sender as RealVitalIcon).SelfVital;
            (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel.SelectedVitalModel = p;
            RealTimeDialogCtrl.Instance._realtime.DataContext = (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel;
            DrugAndEventWindow.Instance.CusContent = RealTimeDialogCtrl.Instance;
            DrugAndEventWindow.Instance.ShowDialog();
        }

        public void ClickShowDialog(PatientVitalSignsModel p)
        {
            if (p != null)
            {
                (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel.SelectedVitalModel = p;
              
            }
            else
            {
                (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel.SelectedVitalModel = null;
            }
            if (!((DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel.VitalCtrlList.Count > 0))
            {
                (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel.InitialVitalCtrlList();
            }
            RealTimeDialogCtrl.Instance._realtime.DataContext = (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[CurPage].RealTimeSignShowCtrlViewModel;
            DrugAndEventWindow.Instance.CusContent = RealTimeDialogCtrl.Instance;
            DrugAndEventWindow.Instance.ShowDialog();
        }

        private int FindNoEmptyValue(List<RealVitalIcon> listIcon, int start)
        {
            int index = -1;
            int count = listIcon.Count;
            for (int i = start; i < count; i++)
            {
                if (!string.IsNullOrEmpty((listIcon[i].DataContext as PatientVitalSignsModel).ModValue))
                {
                    index = i;
                    break;
                }
            }
            return index;
        }

        private int FindNoEmptyValue(List<PatientVitalSignsModel> list, int start)
        {
            int index = -1;
            int count = list.Count;
            for (int i = start; i < count; i++)
            {
                if (!string.IsNullOrEmpty(list[i].ModValue))
                {
                    index = i;
                    break;
                }
            }
            return index;
        }

        private void CreateConnectionLine(string groupBy, List<RealVitalIcon> listIcon = null)
        {
            List<RealVitalIcon> _listIcon = new List<RealVitalIcon>();
            int count = CanvasList.Count;
            if (listIcon == null)
            {
                int delCount = 0;
                for (int i = 0; i < count; i++)
                {
                    FrameworkElement ctrl = CanvasList[i - delCount];
                    if (ctrl is ConnectingLine)
                    {
                        ConnectingLine temp = ctrl as ConnectingLine;
                        if (temp.Group.Equals(groupBy))
                        {
                            CanvasList.RemoveAt(i - delCount);
                            delCount++;
                        }
                    }
                    if (ctrl is RealVitalIcon)
                    {
                        RealVitalIcon temp = ctrl as RealVitalIcon;
                        if (temp.SelfVital.Group.Equals(groupBy))
                        {
                            _listIcon.Add(temp);
                        }
                    }
                }
            }
            else
            {
                _listIcon = listIcon;
            }
            SortedList(_listIcon);
            count = _listIcon.Count;
            for (int i = 0; i < count;)
            {
                if (i == count - 1) break;
                int nextIndex = i + 1;
                RealVitalIcon selfCtrl = _listIcon[i];
                if (selfCtrl.GetType().ToString().Equals("AnesSystem.Controls.TableCellCtrl"))
                {
                    return;
                }
                PatientVitalSignsModel self = selfCtrl.DataContext as PatientVitalSignsModel;
                if (!string.IsNullOrEmpty(self.ModValue))
                {
                    RealVitalIcon nextCtrl = _listIcon[nextIndex];
                    PatientVitalSignsModel nextModel = nextCtrl.DataContext as PatientVitalSignsModel;

                    if (string.IsNullOrEmpty(nextModel.ModValue))
                    {
                        i++;
                        continue;
                        //int index = FindNoEmptyValue(_listIcon, nextIndex);
                        //if (index == -1)
                        //{
                        //    i = nextIndex;
                        //    continue;
                        //}
                        //else
                        //{
                        //    nextIndex = index;
                        //    nextCtrl = _listIcon[nextIndex];
                        //    nextModel = nextCtrl.DataContext as PatientVitalSignsModel;
                        //}
                    }
                    ConnectingLine line = new ConnectingLine();
                    line.Stroke = nextCtrl.DefaultColor;
                    line.Group = self.Group;
                    line.Tag = self;
                    //double nextY = nextCtrl.CanvasTop;
                    //double selfY = selfCtrl.CanvasTop;
                    //double y = nextY - selfY;

                    //double Q = Math.Atan2(y, LocationUtil.RealTimeItem_Width) * (180 / Math.PI);

                    //double chaY = selfCtrl.Height / 2 * Math.Sin(Math.PI * (Q / 180));
                    //double chaX = selfCtrl.Height / 2 * Math.Cos(Math.PI * (Q / 180));

                    //double X1 = selfCtrl.CanvasLeft + chaX;
                    //double Y1 = selfCtrl.CanvasTop + chaY;

                    //double X2 = selfCtrl.CanvasLeft - chaX;
                    //double Y2 = selfCtrl.CanvasTop -chaY;


                    //selfCtrl.RightPoint = new Point(X1,Y1);
                    //nextCtrl.LeftPoint = new Point(X2, Y2);

                    line.SetBinding(ConnectingLine.X1Property, new Binding("X1")
                    {
                        Source = selfCtrl,
                        Mode = BindingMode.TwoWay
                    });
                    line.SetBinding(ConnectingLine.Y1Property, new Binding("Y1")
                    {
                        Source = selfCtrl,
                        Mode = BindingMode.TwoWay
                    });
                    line.SetBinding(ConnectingLine.X2Property, new Binding("X2")
                    {
                        Source = nextCtrl,
                        Mode = BindingMode.TwoWay
                    });
                    line.SetBinding(ConnectingLine.Y2Property, new Binding("Y2")
                    {
                        Source = nextCtrl,
                        Mode = BindingMode.TwoWay
                    });
                    CanvasList.Add(line);
                }
                i = nextIndex;
            }
        }

        private void SortedList(List<RealVitalIcon> _listIcon)
        {
            _listIcon.Sort((RealVitalIcon o1, RealVitalIcon o2) =>
            {
                if (((PatientVitalSignsModel)o1.DataContext).CaptureTime < ((PatientVitalSignsModel)o2.DataContext).CaptureTime)
                {
                    return -1;
                }
                else
                {
                    return 1;
                }
            });
        }
        private int CalValue2Xplot(PatientVitalSignsModel iItem)
        {
            DateTime startTime = new DateTime();
            if (iItem.IsAorP.Equals(Constants.ISANES))
            {
                DateTime anesRecordTime = DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime;
                startTime = anesRecordTime.AddHours((CurPage - 1) * 4);
            }
            if (iItem.IsAorP.Equals(Constants.ISPACU))
            {
                DateTime pacuRecordTime = DataManager.Instance.CurrentPatientLink.Status.PacuStartTime;
                startTime = pacuRecordTime.AddHours((CurPage - 1) * 4);
            }
            TimeSpan span = iItem.CaptureTime - startTime;
            double span1 = span.Minutes + span.Hours * 60 + span.Days * 24 * 60;
            double x = span1 / 5 * LocationUtil.RealTimeItem_Width - 10 / 2;
            return Convert.ToInt32(x);
        }

        private int CalValue2Yplot(PatientVitalSignsModel iItem)
        {
            if (string.IsNullOrEmpty(iItem.ModValue)) return 0;
            double value = Convert.ToDouble(iItem.ModValue);
            double lineHeight = LocationUtil.RealTimeSignItem_TotalRows * LocationUtil.RealTimeSignItem_Height;
            return CheckValue2Yplot(Convert.ToInt32(lineHeight - LocationUtil.RealTimeSignItem_Height * value / LocationUtil.SignSpan_Value - 10 / 2));

        }
        private int CheckValue2Yplot(int y)
        {
            if (y < 0)
            {
                return 0;
            }
            else if (y > LocationUtil.RealTimeSignItem_Height * LocationUtil.RealTimeSignItem_TotalRows)
            {
                return LocationUtil.RealTimeSignItem_Height * LocationUtil.RealTimeSignItem_TotalRows;
            }
            else
            {
                return y;
            }
        }

        #endregion

        #region Public/Protected Methods


        public override void InitData()
        {
            CreateTW();
            CreateMMHG();
            InitTimeLins();
            CreateAutoShowCtrls();
            InitVitals();
        }

        public override void Refresh()
        {
            InitData();
        }

        /// <summary>
        /// 改变体征个数，显示需要改变的
        /// </summary>
        public void ChangeVitalTotal()
        {
            CreateAutoShowCtrls();
        }
        /// <summary>
        /// 刷新折线体征
        /// </summary>
        /// <param name="itemGroup"></param>
        public void RefeshItemLineVital(string itemGroup)
        {
            RemoveVitalItemByGroup(itemGroup);

            InitLineVitals(AllVitalList.Where(O => O.Group.Equals(itemGroup)).ToList());
            //          CreateConnectionLine(itemGroup);
        }
        /// <summary>
        /// 刷新表格体征
        /// </summary>
        /// <param name="itemGroup"></param>
        public void RefeshItemTableVital(string itemGroup)
        {
            RemoveVitalItemByGroup(itemGroup);
            InitTableCellVitals(AllVitalList.Where(O => O.Group.Equals(itemGroup)).ToList());
        }

        public void RefreshByGroup(string itemGroup)
        {
            try
            {

                for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
                {
                    (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].RealTimeSignShowCtrlViewModel.RefershDataFromCache();
                }
                RefreshIBPText();
                if (itemGroup.Equals(Constants.RESP))
                {
                    ConfigVitalSignsModel cvs = null;
                    foreach (var item in DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign)
                    {
                        if (item.code.Equals(Constants.PARAM_RESP_CODE))
                        {
                            cvs = item;
                            break;
                        }
                    }
                    if (cvs == null)
                    {
                        foreach (var item in DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign)
                        {
                            if (item.code.Equals(Constants.PARAM_CTRL_RESP_CODE))
                            {
                                cvs = item;
                                break;
                            }
                        }
                    }
                    if (cvs != null)
                    {
                        if (cvs.showWay == Constants.BEDSIDE_SHOW_METHOD_TREND)
                        {
                            RefeshItemLineVital(itemGroup);
                        }
                        else
                        {
                            RefeshItemTableVital(itemGroup);
                        }
                    }
                }
                else
                {
                    ConfigVitalSignsModel cvs = null;
                    foreach (var item in DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign)
                    {
                        if (item.code.Equals(itemGroup))
                        {
                            cvs = item;
                            break;
                        }
                    }
                    if (cvs != null)
                    {
                        if (cvs.showWay == Constants.BEDSIDE_SHOW_METHOD_TREND)
                        {
                            RefeshItemLineVital(itemGroup);
                        }
                        else
                        {
                            RefeshItemTableVital(itemGroup);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Common.LogHelper.Error("the vitalSign refreshByGroup failed group is" + itemGroup, this.GetType(), ex);
            }
        }

        public void RemoveVitalItemBy(string code)
        {
            int count = CanvasList.Count;
            int delCount = 0;
            for (int i = 0; i < count; i++)
            {

                FrameworkElement ctrl = CanvasList[i - delCount];
                if (ctrl is ConnectingLine && ((PatientVitalSignsModel)((ConnectingLine)ctrl).Tag).Code.Equals(code))
                {
                    CanvasList.RemoveAt(i - delCount);
                    delCount++;
                }
                if (ctrl is RealVitalIcon && ((RealVitalIcon)ctrl).SelfVital.Code.Equals(code))
                {
                    CanvasList.RemoveAt(i - delCount);
                    delCount++;
                }
            }
            if (code.Equals(Constants.PARAM_CTRL_RESP_CODE) || code.Equals(Constants.PARAM_RESP_CODE))
            {
                RefreshByGroup(Constants.RESP);
            }
            ChangeVitalTotal();
            RefreshIBPText();
        }
        public void RemoveVitalItemByGroup(string group)
        {
            int count = CanvasList.Count;
            int delCount = 0;
            for (int i = 0; i < count; i++)
            {
                FrameworkElement ctrl = CanvasList[i - delCount];
                if (ctrl is ConnectingLine && ((ConnectingLine)ctrl).Group.Equals(group))
                {
                    CanvasList.RemoveAt(i - delCount);
                    delCount++;
                }
                if (ctrl is RealVitalIcon && ((RealVitalIcon)ctrl).SelfVital.Group.Equals(group))
                {
                    CanvasList.RemoveAt(i - delCount);
                    delCount++;
                }

            }
            ChangeVitalTotal();
            RefreshIBPText();
        }
        public void AddVitalItemByCode(ConfigVitalSignsModel cvs)
        {
            if (cvs.code.Equals(Constants.PARAM_CTRL_RESP_CODE) || cvs.code.Equals(Constants.PARAM_RESP_CODE))
            {
                VitalSignData.RefreshRespEvent();

            }
            List<PatientVitalSignsModel> list = AllVitalList.Where(O => O.Code.Equals(cvs.code)).ToList();

            if (cvs.showWay == Constants.BEDSIDE_SHOW_METHOD_TABLE)
            {
                InitTableCellVitals(list);
            }
            else
            {
                InitLineVitals(list);
            }
            if (cvs.code.Equals(Constants.PARAM_CTRL_RESP_CODE) || cvs.code.Equals(Constants.PARAM_RESP_CODE))
            {
                RefreshByGroup(Constants.RESP);

            }
            ChangeVitalTotal();
            RefreshIBPText();

        }

        public void ShowWayChanged(ConfigVitalSignsModel cvs)
        {
            string code = cvs.code;
            int showWay = cvs.showWay;
            List<PatientVitalSignsModel> changeList = new List<PatientVitalSignsModel>();
            int count = CanvasList.Count;
            int delCount = 0;
            for (int i = 0; i < count; i++)
            {
                FrameworkElement ctrl = CanvasList[i - delCount];

                if (ctrl is ConnectingLine && ((PatientVitalSignsModel)((ConnectingLine)ctrl).Tag).Code.Equals(code))
                {
                    CanvasList.RemoveAt(i - delCount);
                    delCount++;
                }
                if (ctrl is RealVitalIcon && ((RealVitalIcon)ctrl).SelfVital.Code.Equals(code))
                {
                    CanvasList.RemoveAt(i - delCount);
                    changeList.Add(((RealVitalIcon)ctrl).SelfVital);
                    delCount++;
                }
            }
            if (showWay == Constants.BEDSIDE_SHOW_METHOD_TABLE)
            {
                InitTableCellVitals(changeList);
            }
            else
            {
                RefreshTaableCellIndex();
                InitLineVitals(changeList);
            }
            if (cvs.code.Equals(Constants.PARAM_RESP_CODE) || cvs.code.Equals(Constants.PARAM_CTRL_RESP_CODE))
            {
                RefreshByGroup(Constants.RESP);
            }
            ChangeVitalTotal();
            RefreshIBPText();


        }
        /// <summary>
        /// 表格转为折线后，index发生变化
        /// </summary>
        private void RefreshTaableCellIndex()
        {
            foreach (var item in DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign)
            {
                if (item.showWay == Constants.BEDSIDE_SHOW_METHOD_TABLE)
                {
                    if (item.code.Equals(Constants.PARAM_RESP_CODE) || item.code.Equals(Constants.PARAM_CTRL_RESP_CODE))
                    {
                        RefeshItemTableVital(Constants.RESP);
                    }
                    else
                    {
                        RefeshItemTableVital(item.code);
                    }
                }
            }
        }

        public void InitTWMMHGLocation()
        {
            double height = TwList[0].ActualHeight;
            if (height == 0)
            {
                height = 20.32;
                TwList[0].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - height / 2, 0, 0);
                for (int i = 1; i < TwList.Count; i++)
                {
                    TwList[i].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - height, 0, 0);
                }

                MmhgList[0].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - height / 2, 40, 0);
                for (int i = 1; i < MmhgList.Count; i++)
                {
                    MmhgList[i].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - height, 40, 0);
                }
                MmhgList[MmhgList.Count - 1].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - height, 40, LocationUtil.RealTimeSignItem_Height * 2 - height / 2);
            }
            else
            {
                TwList[0].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - TwList[0].ActualHeight / 2, 0, 0);
                for (int i = 1; i < TwList.Count; i++)
                {
                    TwList[i].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - TwList[i].ActualHeight, 0, 0);
                }

                MmhgList[0].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - TwList[0].ActualHeight / 2, 40, 0);
                for (int i = 1; i < MmhgList.Count; i++)
                {
                    MmhgList[i].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - MmhgList[i].ActualHeight, 40, 0);
                }
                MmhgList[MmhgList.Count - 1].Margin = new Thickness(10, LocationUtil.RealTimeSignItem_Height * 2 - MmhgList[MmhgList.Count - 1].ActualHeight, 40, LocationUtil.RealTimeSignItem_Height * 2 - TwList[0].ActualHeight / 2);
            }

        }

        public void AddSubRespSignsCtrl()
        {
            bool exit = false;
            for (int i = 0; i < AutoShowCtrlList.Count; i++)
            {
                if (((ConfigVitalSignsModel)AutoShowCtrlList[i].DataContext).code.Equals(Constants.PARAM_SUB_RESP))
                {
                    exit = true;
                    break;
                }
            }
            if (exit)
            {
                return;
            }
            StackPanel panel = new StackPanel();
            panel.Orientation = Orientation.Horizontal;
            if (!DataManager.Instance.Code2signs.ContainsKey(Constants.PARAM_SUB_RESP))
            {
                return;
            }
            ConfigVitalSignsModel item = DataManager.Instance.Code2signs[Constants.PARAM_SUB_RESP];
            string fullName = "AnesSystem.Controls." + item.iconCtrl;
            Type type = Type.GetType(fullName);
            if (type == null) return;
            RealVitalIcon ctrl = Activator.CreateInstance(Type.GetType(fullName)) as RealVitalIcon;
            panel.Children.Add(ctrl);
            TextBlock lb = new TextBlock();
            lb.Text = item.name;
            lb.FontFamily = new FontFamily("Microsoft YaHei UI");
            lb.Margin = new Thickness(5, 0, 0, 0);
            panel.Children.Add(lb);
            panel.Margin = new Thickness(5, 10, 0, 0);
            panel.DataContext = item;
            AutoShowCtrlList.Add(panel);
        }

        public void RemoveSubRespSignsCtrl()
        {
            int index = -1;
            for (int i = 0; i < AutoShowCtrlList.Count; i++)
            {
                if (((ConfigVitalSignsModel)AutoShowCtrlList[i].DataContext).code.Equals(Constants.PARAM_SUB_RESP))
                {
                    index = i;
                    break;
                }
            }
            if (index != -1)
            {
                AutoShowCtrlList.RemoveAt(index);
            }
        }


        #endregion

        #region EventHandlers

        #endregion
    }
}
